import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { authApi } from '@/api/user';
import tokenObj from '@/utils/token';
import type { ApiResponse } from '@/types/api';

export const loginAsync = createAsyncThunk(
    "authSlice/loginAsync",
    async (params: Parameters<typeof authApi.login>[0], thunkAPI) => {
        try {
            console.log("loginAsync:", params);
            const res = await authApi.login(params);
            console.log(4444, res);
            return res
        } catch (error) { 
            return thunkAPI.rejectWithValue(error);
        }
    }
);

interface AuthState {
    token: string;
    isLoading: boolean;
    error: string | null;
}
const authslice = createSlice({
    name: "authSlice",
    initialState: {
        token: tokenObj.getToken() || "",
        isLoading: false,
        error: null,
    } as AuthState,
    reducers: {
        setToken(state, action) {
            state.token = action.payload
        },
        logout(state){
            state.token = ""
            tokenObj.removeAuth()
        },
        setLoading(state, action){
            state.isLoading = action.payload
        },
        setError(state, action){
            state.error = action.payload
        }
    },
    extraReducers: (builder) => {
        builder
            .addCase(loginAsync.pending, (state) => {
                state.isLoading = true
                state.error = null
            })
            .addCase(loginAsync.fulfilled, (state, action) => {
                state.isLoading = false
                state.token = action.payload.accessToken
                tokenObj.setAuth(action.payload.accessToken, action.payload.refreshToken)
            })
            .addCase(loginAsync.rejected, (state, action) => {
                state.isLoading = false
                state.error = (action.payload as ApiResponse).message || "登录失败"
            })
    }
})
export const { setToken, logout, setLoading, setError } = authslice.actions
export default authslice.reducer
